//
//  PainterUserAVG.m
//  ChartRefactor
//
//  Created by CaoJun on 15/3/25.
//  Copyright (c) 2015年 CaoJun. All rights reserved.
//

#import "PainterUserAVG.h"

using namespace std;
using namespace ytx;

@implementation PainterUserAVG

- (void)drawEconomicCalendarBanner:(CGRect)cgrect withContext:(ChartCanvas *) ctx withViewModelIndexPosition:(ViewModelIndexPosition *) indexPosition withEconomicCalendarDataSeletedIndex:(NSNumber *) selectedIndex
{
    AVGData * avgData = (AVGData *)indexPosition->getData();
    
    YTXConfig * config = YTXConfig::getInstance();
    ytx::Style style = config->style;
    Rectangle & rect = indexPosition->getRectangle();
    
    float radius = style.AVGEconomicCalendarRadius;
    float fontSize = style.AVGEconomicCalendarTextFont;
    NSString * color = [NSString stringWithUTF8String:style.AVGEconomicCalendarTextColor.c_str()];
    NSString * font = [NSString stringWithUTF8String:style.font.c_str()];
    
    
    vector<EconomicCalendarData> economicCalendarList = avgData->getEconomicCalendarDataList();
    float dy = rect.getEndY();
    float dx = 0;
    
    vector<pair<int, int> > data;
    pair<int, int> last = make_pair(-1, -1);
    
    for (std::vector<EconomicCalendarData>::iterator it = economicCalendarList.begin(); it != economicCalendarList.end(); ++it){
        int index = avgData->getIndexByTimeDuration((*it).ecTime.time_of_day());
        int ecIndex = int(it - economicCalendarList.begin());
        if ( index > 0 ){
            if (ecIndex != [selectedIndex integerValue]) {
                data.push_back(make_pair(index, ecIndex));
            }
            else {
                last = make_pair(index, ecIndex);
            }
        }
    }
    
    if (last.first > -1) {
        data.push_back(last);
    }
    
    for (vector<pair<int, int> >::iterator it = data.begin(); it != data.end(); ++it) {
        pair<int, int> item = (*it);
        float index = item.first;
        int ecIndex = item.second;
        
        dx = rect.getViewPxByViewIndex(index);
        
        [ctx fillCircleWithX:dx withY:dy withRadius:radius withFillColor:[self getEconomicCalendarDataBannerColor:ecIndex withEconomicCalendarDataSeletedIndex:[selectedIndex integerValue]]];
        [ctx fillText:[NSString stringWithFormat:@"%d", ecIndex+1] withX:dx withY:dy withColor:color withFont:font withSize:fontSize withAnchor:CenterMiddle];
    }
    
}

- (NSString *) getEconomicCalendarDataBannerColor:(NSInteger) index withEconomicCalendarDataSeletedIndex:(NSInteger)economicCalendarDataSeletedIndex
{
    YTXConfig * config = YTXConfig::getInstance();
    ytx::Style style = config->style;
    
    string color =  index == economicCalendarDataSeletedIndex ? style.AVGEconomicCalendarFillColorSelected : style.AVGEconomicCalendarFillColorDefault;
    
    return [NSString stringWithUTF8String:color.c_str()];
}

- (void)drawBuyPointsWithinRect:(CGRect)cgrect withContext:(ChartCanvas *)ctx withViewModelIndexPosition:(ViewModelIndexPosition *)indexPosition
{
    AVGData *avgData = dynamic_cast<AVGData *>(indexPosition->getData());
    if (!avgData) {
        return;
    }
    const ytx::Style &style = ytx::YTXConfig::getInstance()->style;
    const CGFloat lineWitdh = style.buyLineWidth;
    NSString *lineColor = [NSString stringWithUTF8String:style.buyLineColor.c_str()];
    const Rectangle &rect = indexPosition->getRectangle();
    const CGFloat x1 = rect.getBeginX();
    const CGFloat x2 = rect.getEndX();
    const list<double> &buyPoints = avgData->getBuyPoints();
    
    const CGFloat centerX = rect.getCenterX();
    NSString *textColor = [NSString stringWithUTF8String:style.buyPointTextColor.c_str()];
    
    for (list<double>::const_iterator it = buyPoints.begin(); it != buyPoints.end(); ++it) {
        const double buyPoint = *it;
        const CGFloat y = rect.getPxY(buyPoint);
        [ctx drawDashLineWidth:lineWitdh color:lineColor x1:x1 y1:y x2:x2 y2:y];
        
        NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"建仓线 %g", buyPoint] attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:style.buyPointTextSize]}];
        NSRange labelRange = NSMakeRange(0, 3);
        [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:labelRange];
        [attributedString addAttribute:NSBackgroundColorAttributeName value:[ChartCanvas colorWithHexString:textColor] range:labelRange];
        [attributedString addAttribute:NSForegroundColorAttributeName value:[ChartCanvas colorWithHexString:textColor] range:NSMakeRange(4, attributedString.length - 4)];
        [ctx fillAttributedString:attributedString atPoint:CGPointMake(centerX, y - 3) anchor:CenterBottom];
    }
}

- (void)drawLimitPositionInfosWithContext:(ChartCanvas *)ctx viewModelIndexPosition:(ytx::ViewModelIndexPosition *)indexPosition
{
    AVGData *avgData = dynamic_cast<AVGData *>(indexPosition->getData());
    if (!avgData) {
        return;
    }
    
    const ytx::Style &style = ytx::YTXConfig::getInstance()->style;
    const CGFloat lineWidth = style.buyLineWidth;
    const Rectangle &rect = indexPosition->getRectangle();
    const CGFloat drawX = rect.getEndX() - rect.getPaddingRight();
    const CGFloat x1 = rect.getBeginX();
    const CGFloat x2 = rect.getEndX();
    NSString *longColorStr = [NSString stringWithUTF8String:style.defaultRed.c_str()];
    NSString *shortColorStr = [NSString stringWithUTF8String:style.defaultGreen.c_str()];
    UIColor *longColor = [ChartCanvas colorWithHexString:longColorStr];
    UIColor *shortColor = [ChartCanvas colorWithHexString:shortColorStr];
    UIFont *font = [UIFont systemFontOfSize:style.buyPointTextSize];
    NSAttributedString *limited = [[NSAttributedString alloc] initWithString:@"限 "
                                                                  attributes:@{
                                                                               NSFontAttributeName:font,
                                                                               NSForegroundColorAttributeName:[UIColor grayColor]
                                                                               }];
    NSString *descTpl = @"%@ %g千克";
    NSString *buyLong = @"做多";
    NSString *buyShort = @"做空";
    const std::list<LimitPositionInfo> &limitPositionInfos = avgData->getLimitPositionInfos();
    
    for (std::list<LimitPositionInfo>::const_iterator it = limitPositionInfos.begin(); it != limitPositionInfos.end(); ++it) {
        const LimitPositionInfo &info = *it;
        const double price = std::get<0>(info);
        const double weight = std::get<1>(info);
        const bool isLong = std::get<2>(info);
        
        const CGFloat y = rect.getPxY(price);
        NSString *colorStr = isLong ? longColorStr : shortColorStr;
        [ctx drawDashLineWidth:lineWidth color:colorStr x1:x1 y1:y x2:x2 y2:y];
        
        NSString *direction = isLong ? buyLong : buyShort;
        UIColor *color = isLong ? longColor : shortColor;
        NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:descTpl, direction, weight]
                                                                                attributes:@{
                                                                                             NSFontAttributeName:font,
                                                                                             NSForegroundColorAttributeName:[UIColor whiteColor],
                                                                                             NSBackgroundColorAttributeName:color
                                                                                             }];
        [str insertAttributedString:limited atIndex:0];
        NSAttributedString *priceAttrStr = [[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@" %g", price]
                                                                           attributes:@{
                                                                                        NSFontAttributeName:font,
                                                                                        NSForegroundColorAttributeName:color
                                                                                        }];
        [str appendAttributedString:priceAttrStr];
        [ctx fillAttributedString:[str copy] atPoint:CGPointMake(drawX, y - 3) anchor:RightBottom];
    }
}

@end
